package com.ty.web;

import com.ty.bean.Users;
import com.ty.service.impl.UsersServiceImpl;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author 田野
 */
@WebServlet(urlPatterns = "/login")
public class LoginServlet extends HttpServlet{
    /**
     * 重写doGet()方法和doPost()方法，或者重写service()方法即可。
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置字符集
        //第一句，设置服务器端编码
        resp.setCharacterEncoding("utf-8");
        //第二句，设置浏览器端解码
        resp.setContentType("text/html;charset=utf-8");
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        // 1、接收参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        // 2、调取service层
        UsersServiceImpl userService = new UsersServiceImpl();
        Users users = userService.login(username, password);
        // 防止用户在为登陆的情况下访问资源

        // 3、跳转页面
        if (users == null){
            // 以弹窗方式提示用户登录失败
            resp.setContentType("text/html;charset=utf-8");
            PrintWriter writer = resp.getWriter();
            writer.print("<script>location.href='login.jsp';alert('用户名或者密码错误')</script>");
            /*writer.print("<script>location.href='login.jsp';</script>");*/

        }else {
            // 保存用户信息
            HttpSession session = req.getSession();
            session.setAttribute("u1", users);
            // 跳转到主页面
            resp.sendRedirect("index.jsp");
        }

    }
}
